import React, { useEffect, useState } from 'react'
import { Card, Button, Row, Col, Statistic, List, Typography, Space, Empty } from 'antd'
import {
  FileTextOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  EditOutlined,
  ThunderboltOutlined,
  VideoCameraOutlined
} from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { StorageFactory } from '../../../services/storage'
import { ContentType } from '../../../types/document'
import { ROUTES } from '../../router/routes'

const { Title, Text } = Typography

interface QuickAction {
  key: string
  title: string
  description: string
  icon: React.ReactNode
  route: string
  color: string
}

interface RecentDocument {
  id: string
  title: string
  type: ContentType
  updatedAt: Date
}

/**
 * 工作台首页
 * 提供快速创建入口、最近文档和统计信息
 */
const HomePage: React.FC = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(true)
  const [recentDocuments, setRecentDocuments] = useState<RecentDocument[]>([])
  const [statistics, setStatistics] = useState({
    total: 0,
    textDocuments: 0,
    storyboards: 0
  })

  // 加载数据
  useEffect(() => {
    loadData()
  }, [])

  const loadData = async () => {
    try {
      setLoading(true)

      // 获取存储适配器
      let storage
      try {
        storage = StorageFactory.getAdapter()
      } catch (err) {
        console.warn('[工作台] 存储未初始化,等待初始化完成')
        setStatistics({ total: 0, textDocuments: 0, storyboards: 0 })
        setRecentDocuments([])
        setLoading(false)
        return
      }

      // 获取所有文本文档
      const textResult = await storage.getContents({
        type: [ContentType.TEXT_DOCUMENT]
      })

      if (!textResult.ok) {
        console.error('[工作台] 加载文本文档失败', textResult.error)
        setStatistics({ total: 0, textDocuments: 0, storyboards: 0 })
        setRecentDocuments([])
        return
      }

      const textDocs = textResult.data
      console.log('[工作台] 获取到的文本文档:', textDocs.length, textDocs)

      // 获取所有分镜脚本
      const storyboardResult = await storage.getContents({
        type: [ContentType.STORYBOARD]
      })

      const storyboardDocs = storyboardResult.ok ? storyboardResult.data : []
      console.log('[工作台] 获取到的分镜脚本:', storyboardDocs.length)

      // 合并所有文档并按更新时间排序取前5个
      const allDocs = [...textDocs, ...storyboardDocs]
      const recentDocs: RecentDocument[] = allDocs
        .map(item => ({
          id: item.id,
          title: item.title || '无标题文档',
          type: item.type,
          updatedAt: item.updatedAt
        }))
        .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())
        .slice(0, 5)

      setRecentDocuments(recentDocs)

      // 统计数据
      setStatistics({
        total: textDocs.length + storyboardDocs.length,
        textDocuments: textDocs.length,
        storyboards: storyboardDocs.length
      })

      console.log('[工作台] 统计数据:', {
        total: textDocs.length + storyboardDocs.length,
        textDocuments: textDocs.length,
        storyboards: storyboardDocs.length
      })
    } catch (error) {
      console.error('[工作台] 加载数据失败', error)
      setStatistics({ total: 0, textDocuments: 0, storyboards: 0 })
      setRecentDocuments([])
    } finally {
      setLoading(false)
    }
  }

  // 快速创建操作
  const quickActions: QuickAction[] = [
    {
      key: 'text',
      title: '文本稿件',
      description: '创建AI辅助的文本内容',
      icon: <FileTextOutlined style={{ fontSize: 24 }} />,
      route: ROUTES.TEXT_EDITOR,
      color: '#1890ff'
    },
    {
      key: 'spark',
      title: '一键火花',
      description: '引导式AI创作流程',
      icon: <ThunderboltOutlined style={{ fontSize: 24 }} />,
      route: '/text/spark',
      color: '#faad14'
    },
    {
      key: 'storyboard',
      title: '分镜脚本',
      description: '视频分镜创意设计',
      icon: <VideoCameraOutlined style={{ fontSize: 24 }} />,
      route: ROUTES.STORYBOARD,
      color: '#52c41a'
    }
  ]

  // 打开文档
  const handleOpenDocument = (doc: RecentDocument) => {
    navigate(`${ROUTES.TEXT_EDITOR}?id=${doc.id}`)
  }

  // 查看所有文档
  const handleViewAllDocuments = () => {
    navigate(ROUTES.TEXT_DOCUMENT_LIST)
  }

  // 格式化时间
  const formatTime = (date: Date) => {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString('zh-CN')
  }

  return (
    <div style={{
      padding: '32px 48px',
      height: '100%',
      overflow: 'auto',
      background: '#f5f5f5'
    }}>
      {/* 标题区域 */}
      <div style={{ marginBottom: 32 }}>
        <Title level={2} style={{ marginBottom: 8 }}>工作台</Title>
        <Text type="secondary" style={{ fontSize: 16 }}>
          融媒智创工坊 - AI驱动的智能内容创作平台
        </Text>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={8}>
          <Card hoverable>
            <Statistic
              title="文档总数"
              value={statistics.total}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card hoverable>
            <Statistic
              title="文本稿件"
              value={statistics.textDocuments}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card hoverable>
            <Statistic
              title="分镜脚本"
              value={statistics.storyboards}
              prefix={<VideoCameraOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容区域 */}
      <Row gutter={[16, 16]}>
        {/* 快速创建 */}
        <Col xs={24} lg={14}>
          <Card
            title={
              <Space>
                <PlusOutlined />
                <span>快速创建</span>
              </Space>
            }
            styles={{ body: { padding: 24 } }}
          >
            <Row gutter={[16, 16]}>
              {quickActions.map(action => (
                <Col xs={24} sm={8} key={action.key}>
                  <Card
                    hoverable
                    onClick={() => navigate(action.route)}
                    style={{
                      textAlign: 'center',
                      borderColor: action.color,
                      cursor: 'pointer'
                    }}
                    styles={{ body: { padding: '24px 16px' } }}
                  >
                    <div style={{ color: action.color, marginBottom: 12 }}>
                      {action.icon}
                    </div>
                    <Title level={5} style={{ marginBottom: 8 }}>
                      {action.title}
                    </Title>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {action.description}
                    </Text>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>

        {/* 最近使用 */}
        <Col xs={24} lg={10}>
          <Card
            title={
              <Space>
                <ClockCircleOutlined />
                <span>最近使用</span>
              </Space>
            }
            extra={
              recentDocuments.length > 0 && (
                <Button
                  type="link"
                  size="small"
                  onClick={handleViewAllDocuments}
                >
                  查看全部
                </Button>
              )
            }
            styles={{
              body: {
                padding: recentDocuments.length === 0 ? 24 : 0,
                maxHeight: 400,
                overflow: 'auto'
              }
            }}
          >
            {loading ? (
              <div style={{ textAlign: 'center', padding: 40 }}>
                <Text type="secondary">加载中...</Text>
              </div>
            ) : recentDocuments.length === 0 ? (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description="暂无最近文档"
                style={{ padding: '20px 0' }}
              >
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => navigate(ROUTES.TEXT_EDITOR)}
                >
                  创建文档
                </Button>
              </Empty>
            ) : (
              <List
                dataSource={recentDocuments}
                renderItem={item => (
                  <List.Item
                    style={{
                      cursor: 'pointer',
                      padding: '12px 24px',
                      transition: 'background 0.3s'
                    }}
                    onClick={() => handleOpenDocument(item)}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = '#fafafa'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = 'transparent'
                    }}
                  >
                    <List.Item.Meta
                      avatar={
                        <FileTextOutlined
                          style={{
                            fontSize: 20,
                            color: '#1890ff'
                          }}
                        />
                      }
                      title={
                        <div style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: 8
                        }}>
                          <Text strong ellipsis style={{ flex: 1 }}>
                            {item.title}
                          </Text>
                        </div>
                      }
                      description={
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {formatTime(item.updatedAt)}
                        </Text>
                      }
                    />
                    <Button
                      type="text"
                      size="small"
                      icon={<EditOutlined />}
                      onClick={(e) => {
                        e.stopPropagation()
                        handleOpenDocument(item)
                      }}
                    >
                      打开
                    </Button>
                  </List.Item>
                )}
              />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default HomePage
